import FmSocket from './FmSocket.js';

// eslint-disable-next-line import/no-cycle
import FmMonitorBase from './FmMonitorBase';

let localId;
let _webSocketUrl;
let _weksocket;

// 回放相关内容
// let _playbackTimer = null; // 回放定时器
// let _curPackageIndex = 0;
// let _allTime = 0; // 总的时间
// let _sToCount = 0; // 每秒运行多少次

let curPackageIndex = 0;
class FeimaMonitor extends FmMonitorBase {
  constructor(options) {
    super(options);
    // 请求数据
    localId = options.local_id;
    _webSocketUrl = options.url;
    this.playbackTimer = null; // 回放定时器
    this.options = options;
    this.totalCount = 0;
    this.getDeviceDetail(this.flightMission);
  }

  // 初始化并连接websocket
  openSocket(websocketData) {
    const msg = this.getSendMessageFun(this.flightMission ? this.flightMission.user_id : '', localId);
    const socketOptions = {
      platform: this.platform,
      url: _webSocketUrl,
      msg,
    };
    if (!_webSocketUrl) {
      console.log('websocket地址获取失败');
      return;
    }
    _weksocket = new FmSocket(socketOptions);
    _weksocket.open();
    _weksocket.onMessage = (res) => {
      const {data} = JSON.parse(res.data);
      if (data) {
        const time = data.flight_mission_id[0][0] ? data.flight_mission_id[0][0] : '';
        if (time) {
          this.flightPanelDatas.updated_at = this.getUpdate(time); // 更新时间  更新
        }
        this.updateDatItem(data);
      }
    };
    _weksocket.onError((err) => {
      this.onErrorSocket(err);
    });
  }

  /**
   * 关闭Socket
   */
  closeSocket() {
    _weksocket.close();
  }

  /**
   * 连接错误
   */
  onErrorSocket(err) {}

  /**
   * 获取发送的指令
   * @returns {string}
   * @private
   */
  getSendMessageFun(userId, missionLocalId) {
    return '{"uid":"' + userId + '","flight_mission_id":"' + missionLocalId + '"}';
  }

  /**
   * 航线数据处理
   * */
  getDeviceDetail(flightMission) {
    // 初始各项数据
    if (flightMission) {
      this.initDatas(flightMission);
    }

    if (!flightMission || !flightMission.flight_log) {
      this.openSocket();
    }
  }

  /** 回放数据处理 */
  getBackData(data) {
    if (this.playbackTimer) {
      clearInterval(this.playbackTimer);
    }
    const totalCount = data.flight_log.packages.length;
    this.totalCount = totalCount;
    this.playbackTimer = setInterval(() => {
      if (curPackageIndex < totalCount) {
        // 获取持续时间
        const {packages} = data.flight_log;
        const dataItem = packages[curPackageIndex];
        dataItem.created_str
          ? this.updateLogDataItem([[[Number(dataItem.created_str), JSON.stringify(dataItem.data[0])]]])
          : this.updateLogDataItem([[[Number(new Date(dataItem.created_at)), JSON.stringify(dataItem.data)]]]);
        curPackageIndex++;
      } else {
        clearInterval(this.playbackTimer);
      }
    }, 62.5);
  }

  /**
   * 回放相关
   */
  /**
   * 回放时根据时间戳获取更新时间。
   * @param {时间戳} date
   * @returns
   */
  getUpdate(date) {
    const time = new Date(date);
    const y = time.getFullYear();
    const m = time.getMonth() + 1;
    const d = time.getDate();
    const h = time.getHours();
    const mm = time.getMinutes();
    const s = time.getSeconds();
    return add0(h) + ':' + add0(mm) + ':' + add0(s);
  }

  // 回放初始化
  initPlayback() {
    clearInterval(this.playbackTimer);
    this.playbackTimer = null;
    curPackageIndex = 0;
  }

  /**
   * 暂停播放
   */
  pausePlayBack() {
    clearInterval(this.playbackTimer);
    this.playbackTimer = null;
    this.initLastUpdateTime();
  }

  /**
   * 开始播放
   */
  openPlayBack() {
    this.isBackPlay = true;
    this.getBackData(this.flightMission);
  }

  /** 移动 */
  setPlaybackProgress(precent) {
    return new Promise((resolve, reject) => {
      this.pausePlayBack();

      this.clearPath();
      const data = this.options.flight_data;
      const newCurPackageIndex = Math.ceil(this.totalCount * precent);

      for (let i = 0; i < newCurPackageIndex; i++) {
        const dataItem = data.flight_log.packages[i];
        // this.updateDatItem([[[Number(dataItem.created_str),JSON.stringify(dataItem.data[0]) ]]]);
        this.updatelocation(dataItem.data);
      }
      curPackageIndex = newCurPackageIndex;
      setTimeout(() => {
        this.getBackData(this.flightMission);
      }, 1000);

      resolve(true);
    });
  }

  /**
   * 回放的更新航线和里程
   * @param {Object} position, {latitude, longitude}
   */
  updatePlaybackPosition(position) {
    const {longitude: lng, latitude: lat, altitude: alt} = position;
    const val = this.getWgs84Position({lng, lat, alt});
    // 触发回放改变事件
    this.onPositionUpdated(val);
  }

  // 进度条改变事件监听
  onPlaybackPercentChanged(percent) {}
}
/**
 * 判断是否要加0
 * @param {时，分，秒} m
 * @returns
 */
function add0(m) {
  return m < 10 ? '0' + m : m;
}

function formatSecondsToHours(seconds) {
  const MINUTES = 60;
  const HOURS = 3600;
  const tHours = parseInt(seconds / HOURS, 10);
  const tMinutes = parseInt(seconds / MINUTES, 10);
  const tSeconds = parseInt(seconds - tHours * HOURS - tMinutes * MINUTES, 10);

  const nDate = new Date(1, 1, 1, tHours, tMinutes, tSeconds);
  const nYear = nDate.getFullYear();
  const nMonth = nDate.getMonth() + 1;
  const nDay = nDate.getDate();
  const nHours = nDate.getHours();
  const nMinutes = nDate.getMinutes();
  const nSeconds = nDate.getSeconds();

  const timeStr = `${nYear}-${add0(nMonth)}-${add0(nDay)} ${add0(nHours)}:${add0(nMinutes)}:${add0(nSeconds)}`;
  const hhmmss = timeStr.slice(11);
  return hhmmss;
}
export default FeimaMonitor;
